import { Session, SessionEvents } from '../src/session';
import { InMemoryProvider } from '../src/transport';
import { ToolRegistry, builtInTools } from '../src/tools';
import { InMemoryMemoryStore } from '../src/memory';
import { NodeBuilder, TurnAnalyzer, TextAggregator } from '../src/helpers';
import { TurnStatus, NodeType } from '../src/types';

async function main() {
  console.log('🎯 Events & Real-time Updates Demo\n');

  // Setup event handlers
  const events: SessionEvents = {
    onNode: (turnId, node) => {
      console.log(`📨 [${turnId.slice(-6)}] New node: ${node.type}`);
      
      switch (node.type) {
        case NodeType.RawResponse:
          console.log(`   💬 Text: "${(node as any).text}"`);
          break;
        case NodeType.ToolUse:
          const toolNode = node as any;
          console.log(`   🔧 Tool: ${toolNode.tool}`);
          if (toolNode.result) {
            console.log(`   ✅ Success: ${JSON.stringify(toolNode.result).slice(0, 50)}...`);
          }
          if (toolNode.error) {
            console.log(`   ❌ Error: ${toolNode.error}`);
          }
          break;
        case NodeType.AgentMemory:
          console.log(`   💭 Memory: "${(node as any).content}"`);
          break;
        case NodeType.SuggestedQuestions:
          console.log(`   ❓ Questions: ${(node as any).questions.length} suggested`);
          break;
      }
    },

    onTurnStatusChange: (turnId, status, turn) => {
      console.log(`🔄 [${turnId.slice(-6)}] Status: ${status}`);
      
      if (status === TurnStatus.Success) {
        const summary = TurnAnalyzer.getSummary(turn.nodes);
        console.log(`   📊 Summary: ${summary.textLength} chars, ${summary.toolsUsed} tools, ${summary.memoriesCreated} memories`);
      }
    },

    onError: (turnId, error) => {
      console.log(`💥 [${turnId.slice(-6)}] Error: ${error.message}`);
    }
  };

  // Setup session with events
  const provider = new InMemoryProvider();
  const tools = new ToolRegistry();
  const memories = new InMemoryMemoryStore();

  Object.values(builtInTools).forEach(tool => tools.register(tool));

  const session = new Session({ 
    model: provider, 
    tools, 
    memories, 
    allowAutoTools: true,
    events 
  });

  console.log('🚀 Starting conversation with real-time events...\n');

  // Send first message
  const turnId1 = await session.send({ 
    requestMessage: 'Help me understand this codebase' 
  });

  // Wait for completion
  await new Promise(r => setTimeout(r, 200));

  console.log('\n📈 Turn Analysis:');
  const fullText = session.getFullText(turnId1);
  const suggestions = session.getSuggestedQuestions(turnId1);
  const toolResults = session.getToolResults(turnId1);

  console.log(`   Full text (${fullText.length} chars): "${fullText}"`);
  console.log(`   Suggestions: ${suggestions.join(', ')}`);
  console.log(`   Tool results: ${toolResults.length} tools executed`);

  // Demonstrate resend functionality
  console.log('\n🔄 Testing resend functionality...');
  const turnId2 = await session.resendTurn(turnId1);
  
  await new Promise(r => setTimeout(r, 200));

  console.log('\n📋 Final session state:');
  const allTurns = session.listTurns();
  allTurns.forEach(turn => {
    const summary = TurnAnalyzer.getSummary(turn.nodes);
    console.log(`   Turn ${turn.id.slice(-6)}: ${turn.status} - ${summary.textLength} chars, ${turn.nodes.length} nodes`);
  });

  // Check memory store
  const pendingMemories = memories.listByState('pending');
  console.log(`\n💭 Memory store: ${pendingMemories.length} pending memories`);
  pendingMemories.forEach(mem => {
    console.log(`   - ${mem.id}: "${mem.content.slice(0, 50)}..."`);
  });
}

main().catch(console.error);
